Page({
  data: {
    // 用户信息
    userInfo: [],
    theme: null,
    // 训练经验选项
    experienceLevels: [
      { id: 1, name: "零基础" },
      { id: 2, name: "初学者(1年以内)" },
      { id: 3, name: "中级(1-3年)" },
      { id: 4, name: "高级(3年以上)" }
    ],
    // 当前选中的目标索引
    selectedGoalIndex: 0,
    // 当前选中的经验索引
    selectedExperienceIndex: 0
  },

  // 页面加载时获取用户信息
  onLoad() {
    // 从本地存储获取用户信息
    const userInfo = wx.getStorageSync('userInfo') || {};
    console.log("信息是：",userInfo)
    this.setData({
      userInfo: userInfo,
      // 设置默认选中项
      //selectedGoalIndex: this.getGoalIndex(userInfo.fitnessGoal),
      //selectedExperienceIndex: this.getExperienceIndex(userInfo.experience)
    });
  },

  // 获取目标索引
  getGoalIndex(goalName) {
    if (!goalName) return 0;
    return this.data.fitnessGoals.findIndex(item => item.name === goalName);
  },

  // 获取经验索引
  getExperienceIndex(expName) {
    if (!expName) return 0;
    return this.data.experienceLevels.findIndex(item => item.name === expName);
  },

  // 选择头像
  chooseAvatar() {
    wx.chooseMedia({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        // 返回选定照片的本地文件路径列表
        const tempFilePaths = res.tempFilePaths;
        this.setData({
          'userInfo.avatarUrl': tempFilePaths[0]
        });
      }
    });
  },


  // 训练经验改变
  onExperienceChange(e) {
    const index = e.detail.value;
    this.setData({
      selectedExperienceIndex: index,
      'userInfo.experience': this.data.experienceLevels[index].name
    });
  },

  // 保存用户信息
  saveUserInfo(e) {
    const formData = e.detail.value;
    // 验证必填项
    if (!formData.nickname || formData.nickname.trim() === '') {
      wx.showToast({
        title: '请输入用户名',
        icon: 'none',
        duration: 2000
      });
      wx.request({
        url: getApp().globalData.baseUrl+'/api/user/updateUser/'+this.data.userInfo.data.id,
        method: 'POST',
        data: {},
        header: {
          'Content-Type': 'application/json',
        },
        success: (res) => {
          console.log(res.data)
          this.setData({
            userInfo:userInfo
          });
        },
        fail: (err) => {
          console.error('初始化数据获取失败:', err);
          wx.showToast({
            title: '数据加载失败',
            icon: 'none'
          });
        },
        complete: () => {
          // 无论成功失败，都关闭加载提示
          wx.hideLoading();
          this.setData({
            loading: false
          });
        }
      });
      return;
    }
    
    // 合并更新用户信息
    const updatedUserInfo = {
      ...this.data.userInfo,
      ...formData,
      // 保留头像信息
      avatarUrl: this.data.userInfo.avatarUrl || '/images/default-avatar.png'
    };
    
    // 保存到本地存储
    wx.setStorageSync('userInfo', updatedUserInfo);
    
    // 显示保存成功提示
    wx.showToast({
      title: '保存成功',
      icon: 'success',
      duration: 2000
    });
    
    // 延迟返回上一页
    setTimeout(() => {
      wx.navigateBack({
        delta: 1
      });
    }, 1500);
  },
// 新增性别选择方法
// 性别选择处理（单选且可取消）
selectGender(e) {
  const selectedGender = e.currentTarget.dataset.gender;
  const currentGender = this.data.userInfo.gender;
  
  // 判断：如果点击的是已选中的性别，则取消选择；否则选中该性别
  const newGender = currentGender === selectedGender ? '' : selectedGender;
  
  this.setData({
    'userInfo.gender': newGender
  });
  
  // 可选：添加交互反馈
  if (newGender) {
    wx.showToast({
      title: `已选择${newGender === 'male' ? '男' : '女'}`,
      icon: 'none',
      duration: 1000
    });
  } else {
    wx.showToast({
      title: '已取消选择',
      icon: 'none',
      duration: 1000
    });
  }
},

chooseAvatar() {
  wx.chooseMedia({
    count: 1,
    sizeType: ['compressed'], 
    sourceType: ['album', 'camera'],
    success: (res) => {
      const tempFilePaths = res.tempFilePaths;
      this.setData({
        'userInfo.avatarUrl': tempFilePaths[0]
      });
    }
  });
},

});
